<?php
class TeamAction extends IntesysAction {
	
	function _initialize(){
        parent::_initialize();
		$this->dao = D('Member');// 编辑、删除操作需要
    }

	function test(){
		$this->display();
	}
	//团队人员，积分排名
	function index(){
		//当前用户默认查看下属的排名
		
		//查找所有积分来源
		$this->taskform = M('Form') -> where(array('site_id' => __SITEID__)) -> select();
		$this->integraltype = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		
		$this->display();
	}
	private function getMemberposition(){
		$this->dao = M('Member_position');
		$pid = $this->_post('id') ? $this->_post('id') : 0;
		$map['m.pid'] = $pid;
		$map['m.site_id'] = __SITEID__;
		$ret = array();
		$list = $this->dao -> where($map) ->alias('m') -> select();
		foreach($list as $k => $v){
			//查找层级
			
			$sub = $this -> dao -> where(array('pid' => $v['id'])) -> count();
			$isParent = false;
			if($sub > 0){
				$isParent = true;
			}
			$data['isParent'] = $isParent;
			$data['id'] = $v['id'];
			$data['name'] = $v['name'].'';
			$ret[] = $data;
		}
		echo json_encode($ret);
	}
	private function getMember(){
		$pid = $this->_post('id') ? $this->_post('id') : $_GET['id'];
		$map['m.pid'] = $pid;
		$map['m.site_id'] = __SITEID__;
		$ret = array();
		$list = $this->dao -> where($map) ->alias('m') -> select();
		foreach($list as $k => $v){
			//查找层级
			
			$sub = $this -> dao -> where(array('pid' => $v['id'])) -> count();
			$isParent = false;
			if($sub > 0){
				$isParent = true;
			}
			$data['isParent'] = $isParent;
			$data['id'] = $v['id'];
			$data['name'] = $v['name'].'【有'.$sub.'个下级】';
			$ret[] = $data;
		}
		echo json_encode($ret);
	}
	public function membertree(){
		if(IS_POST){
			$this->getMember();
			exit;
		}
		$this->display();
	}
	
	public function memberpositiontree(){
		if(IS_POST){
			$this->getMemberposition();
			exit;
		}
		$this->display();
	}
	//查看下级会员
	 function sindex(){
		$map = 'mm.member_id = '.$this->_get('id');
		$this->id = $this->_get('id');
		$this->getLevelNameList = $this->dao -> getLevelNameList();
		if($this->_get('keywords')){
			$map .= " and (m.nickname like '%".$this->_get('keywords')."%' or m.id = '".$this->_get('keywords')."')";
			$this->keywords = $this->_get('keywords');
		}
		
		if($this->_get('level')){
			if($this->_get('level') != 'all'){
				$map .= " and (mm.level = '".$this->_get('level')."')";
			}
			
			$this->level = $this->_get('level');
		}  
		
		
		$this->initView();
		$db = D('Member_member'); 
		$db -> _list($this->view, $map);
		
		$this->display();
	}
	//编辑会员
	public function edit(){
		// 查找所有积分类型
		$this -> inteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		$this->getLevelNameList = $this->dao -> getLevelNameList();
		$this->position_list=D('Member_position')->getList(['site_id'=>__SITEID__]);
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>__SITEID__));
		$member_role_user = M('Member_role_user')-> where(array('user_id' => $this->_get('id'))) -> select();
		$employee = $this->dao -> where(array('site_id' => __SITEID__, 'id' => $this->_get('id'))) -> find();
		$memberpostionid = trim($employee['memberpostionid'],',');
		$this -> memberpostion = D('Member_position') -> where("site_id = ".__SITEID__. " and id in(".(empty($memberpostionid)?0:$memberpostionid).")") -> select();
		foreach($member_role_user as $k => $v){
			$member_role_userid[] = $v['role_id'];
		}
		$this->member_role_userids = $member_role_userid;
        $this->rule_list=D('Integral_rule')->alias('r')->join('left join __INTEGRAL_RULETYPE__ t on r.type_id = t.id')->where(array('r.site_id'=>__SITEID__,'t.isfix'=>1))->Field('r.*')->select();
		$this->supplierList=M('Supplier')->alias('s')->join('left join __MEMBER_SUPPLIER__ ms ON s.id=ms.supplier_id and ms.member_id='.$this->_get('id')) -> where(array('s.site_id' => __SITEID__)) -> Field('s.*,ms.member_id,ms.supplier_id') -> select();
		if ($this->_get('id')) {
            $map['id'] = array(
                'eq',
                $this->_get('id')
            );
            $info = $this->dao->where($map)->find();
			
			$info['integralconfig'] =  unserialize($info['integralconfig']);
			$this->assign('info', $info);
            $this->display();
        } else {
            $this->error('参数错误');
        }
	}
	//新建会员
	public function add(){
		$this -> inteType = M('Integral_type') -> where(array('site_id' => __SITEID__)) -> select();
		$this->getLevelNameList = $this->dao -> getLevelNameList();
        $this->role_list=D('Member_group')-> getList2(0,0,array('site_id'=>__SITEID__));
        $this->rule_list=D('Integral_rule')->alias('r')->join('left join __INTEGRAL_RULETYPE__ t on r.type_id = t.id')->where(array('r.site_id'=>__SITEID__,'t.isfix'=>1))->Field('r.*')->select();
		parent::add();
	}
	//更新用户信息
	public function update(){
		$member_id = $this->_post('id');
		if($this -> _post('leveldown') == 0){
			M('Member_member') -> where(array('smember_id' => $member_id)) -> data(array('level' => $this->_post('level'))) -> save();
			
		}
		$_POST['integralconfig'] = serialize($_POST['integralconfig']);
		$_POST['memberpostionid'] = ','.implode(',', $_POST['member_position_id']).',';
		
		
        if(trim($_POST['role_id'][0])!=''){$_POST['group_id']=$_POST['role_id'][0];}
		if($member_id){
            if(""!=trim($_POST['password'])){
                $_POST['password']=md5($_POST['password']);    
            }else{
                unset($_POST['password']);
            }
            if(isset($_POST['reg_time'])){$_POST['reg_time']=strtotime($_POST['reg_time']);}
            if(isset($_POST['rule_id'])){$_POST['rule_id']=implode(',',$_POST['rule_id']);}
			if(isset($_POST['role_id'])){
				$data1=$_POST;
				//dump($data);exit(); 
				$role_user=M('Member_role_user');
				$role_user->where(array('user_id'=>$data1['id']))->delete();
				foreach($data1['role_id'] as $k=>$v){
					$r['user_id']=$data1['id'];
					$r['role_id']=$v;
					if(!$role_user->add($r)){
						$flag=false;
					}
				}
			}
            
		    $db = D('member_supplier'); 
			$db -> where(array('member_id' => $member_id, 'site_id' => __SITEID__)) -> delete();
			//重新写入
			foreach($_POST['supplier_id'] as $k => $v){
				$data['supplier_id'] = $v;
				$data['member_id'] = $member_id;
				$data['site_id'] = __SITEID__;
				$db -> add($data);
			}
            
		}
		parent::update();
	}
    public function insert(){
		if($jumpUrl == ''){
			$jumpUrl = (session('jumpUrl')&&session('jumpUrl')!='') ? session('jumpUrl') : U('Admin/' . MODULE_NAME . '/index');
		}
		if(isset($_POST)){
			if(!session(C('ADMIN_AUTH_KEY') )){
			    $_POST['pid'] = session(C('USER_AUTH_KEY'));
			}
			if(isset($_POST['reg_time'])){$_POST['reg_time']=strtotime($_POST['reg_time']);}
            if(isset($_POST['rule_id'])){$_POST['rule_id']=implode(',',$_POST['rule_id']);}
			$_POST['password']=md5($_POST['password']);
			$createret = $this->dao->create();
			
			if(!$createret){
				$this->error($this->dao -> getError());exit;
			}
			
			$id = $this->dao->add();
			
			if(!$id){
				$this->error($this->dao -> getError());exit;
			}
			$data=$_POST;
			$flag=true;
			$role_user=M('Member_role_user');
            $role_user->where(array('user_id'=>$data['id']))->delete();
			foreach($data['role_id'] as $k=>$v){
				$r['user_id']=$id;
				$r['role_id']=$v;
				if(!$role_user->add($r)){
					$flag=false;
				}
			}
			if($flag){
				$this->success('添加成功',$jumpUrl);
			}else{
				$this->error('出错了,可能是数据库链接出错,请检查');
			}
			//parent::insert();
		}
	}
	public function sendMsg(){
	    //显示发送页面
		if($this->_post('ids')){
			$this->ids = explode(',', $this->_post('ids'));
			$count = 0;
			foreach($this->ids as $v){
				if(sendWXMsg($v, $this->_post('msg'))){
					$count ++;
				}
			}
			$ret['status'] = 1;
			$ret['info'] = $count;
			$ret['data'] = '';
			echo json_encode($ret);
		}
	}
	//更新父ID
	public function updatePid(){
		if($this->_post('pid')){
			$pid = $this->_post('pid');
			$member_id = $this -> _post('member_id');
			$ret = $this->dao -> updatePid($member_id, $pid);
			if($ret){
				$this->success('操作成功！');
			}else{
				$this->error('操作失败，该会员的父ID不能更改');
			}
		}else{
			$this->error('参数错误');
		}
	}
	//更新父ID
	public function deletePid(){
		if($this->_get('pid')){
			$pid = $this->_get('pid');
			$member_id = $this -> _get('member_id');
			$ret = $this->dao -> deletePid($member_id, $pid);
			if($ret){
				
				
				M('Member_member') -> where(array('site_id' => __SITEID__, 'member_id'=>$pid, 'smember_id' => $member_id )) -> delete();
				
				
				$this->success('操作成功！');
			}else{
				$this->error('操作失败，该会员的父ID不能更改');
			}
		}else{
			$this->error('参数错误');
		}
	}
	
	public function delete(){
		if(isset($_GET['id']) && intval($_GET['id'])>0){
			M('Member_member') -> where(array('site_id' => __SITEID__, 'smember_id' => $this->_get('id') )) -> delete();
		}
		parent::delete();
		
	}
	
	//添加会员积分
	public function addintegral(){
		$id = $this->_get('id');

		if(IS_POST){
		   $id = $this->_post('id');
		   $integral = $this->_post('integral');
		   import("@.ORG.Integrals.Integral");
		   $Integral = new Integral($id);
		   $mes = $Integral->giveIntegral($integral);
		   if($mes){
				$this->success('操作成功！');
				exit;
			}else{
				$this->error('操作失败');
				exit;
			}
		}
		
		$this->assign('id',$id);
		$this->display();
	}
	
	//会员直接登录
	public function login(){
		$member = $this->dao -> where(array('site_id' => __SITEID__, 'id' => $this-> _get('id'))) -> find();dump($member);
		session('memberInfo', $member);
		redirect('/'.__SITEID__.U('Member/Index/index'));
	} 
	
	public function datalist(){
		$map = "site_id = ". __SITEID__ ."";
		if($this -> _get('keywords')){
			$map .= " and name like '%".$this->_get('keywords')."%'";
		}

		if((D('Member')->where('id = '.$this->memberInfo['id'])->getfield('isadministrator',false))!='1'){
			$position=D('Member')->where('id = '.$this->memberInfo['id'])->getfield('memberpositionid',false);
			$position=array_filter(explode(',',$position));
			$memmap='';
			foreach($position as $key =>$val){
				$memmap.=" memberpositionid like '%".$val."%' or";
			}
			$memmap=substr($memmap,0,-2);
			$map.=' and ('.$memmap.')';
		}
		$this->list = M('Member') -> where($map) -> select();
		$this->display();
	}
	public function membergrouplist(){
		$map = "site_id = ". __SITEID__ ."";
		if($this -> _get('keywords')){
			$map .= " and title like '%".$this->_get('keywords')."%'";
		}
		$this->list = M('Member_group') -> where($map) -> select();
		$this->display();
	}
	//选择列表
	public function select(){
		$this->display();
	}
	//查看排名
	public function ranking(){
        $this->display();
    }
	public function tree(){
		$this->dao = M('Integral_ruletype');
		if($this->_param('keywords')){
			$this->listmap.=" and site_id = '".__SITEID__."' and name like '%".$this->_param('keywords')."%'";
		}else{
			$pid = $this->_get('pid') ? $this->_get('pid') : 0;
			$this->listmap.=" and site_id = '".__SITEID__."' and pid=".$pid;
		}
		$this->listorder = 'id';
		
		$this->initView();
        parent::_list();
		$list=$this->list;
		
		$this->assign('list',$list);
		$str = $this->fetch();
		$list = $this->view -> get('list');
		foreach($list as $k => $v){
			$str = str_replace('<!--sub#'.$v['id'].'-->', $this->treehtml($v['id'],'tree'), $str);
		}
		
		$list = $_GET['list'];
		$empty = 1;
		$statu=$list?1:0;
		if($this->get('list')){ 
			$empty = 0;
		}
		die(json_encode(array('empty' => $empty,'tbody'=>$str,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this-> view -> get('pages'))));
	}
	private function treehtml($pid = 0,$mytree){
		$list = $this->dao -> where(array('site_id' => __SITEID__, 'pid' => $pid)) -> order('id') -> select();
		if($list){
			$this->assign('list', $list);
			$curstr = $this->fetch($mytree);
			foreach($this->list as $k => $v){
			    $curstr = str_replace('<!--sub#'.$v['id'].'-->', $this->treehtml($v['id'],$mytree), $curstr);
		    }
			return $curstr; 
		}
	}
	public function positionlist(){
		$this->dao = M('Member_position');
		if($this->_param('keywords')){
			$this->listmap.=" and site_id = '".__SITEID__."' and name like '%".$this->_param('keywords')."%'";
		}else{
			$this->isadmin=D('Member')->where('id = '.$this->memberInfo['id'].' and site_id ='.__SITEID__)->getfield('isadministrator');
			$poslist=D('Member')->where('id = '.$this->memberInfo['id'].' and site_id ='.__SITEID__)->getfield('memberpositionid');
			$poslist=array_filter(explode(',',$poslist));
			if($this->isadmin != 1){
				$leader=getManagerList();
				if(in_array($this->memberInfo['id'],$leader)){
					$pid=' and pid =0';
				}else{
					$pid=' and pid =0 and member_id ='.$this->memberInfo['id'];
				}
//				foreach($poslist as $k =>$v){
//					$sql.=" or id = ".$v;
//				}
//				$pid=' and pid =0'.' and ( 0'.$sql.')';
			}else{
				$pid=' and pid =0';
			}
			if($this->_get('pid')):$pid=' and pid ='.$this->_get('pid'); endif;
//			$pid = $this->_get('pid') ? $this->_get('pid') : 0;
			$this->listmap.=" and site_id = ".__SITEID__.$pid;
		}
		$this->listorder = 'id';

		$this->initView();
		parent::_list();
		$list=$this->list;

		$this->assign('list',$list);
		$str = $this->fetch();
		$list = $this->view -> get('list');
		foreach($list as $k => $v){
			$str = str_replace('<!--sub#'.$v['id'].'-->', $this->treehtml($v['id'],'positionlist'), $str);
		}
		$list = $_GET['list'];
		$empty = 1;
		$statu=$list?1:0;
		if($this->get('list')){
			$empty = 0;
		}
		die(json_encode(array('empty' => $empty,'tbody'=>$str,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this-> view -> get('pages'))));
	}
	public function departseach(){
		$this->positionlist();
	}
	public function membergroup(){
		$this->dao = M('Member_position');
		if($this->memberInfo['isadministrator']||in_array($this->memberInfo['id'],getManagerList())){
			$pid=0;
		}else{
			//获取部门id
			$pid=D('member')->where('id = '.$this->memberInfo['id'])->getfield('memberpositionid');
			$pid=substr(substr($pid,1),0,-1);//280,281
			if($pid == ''){
				$pid = 0;
			} 
		}
		$this->listmap.=" and site_id = '".__SITEID__."' and id in (".$pid.")";
		$this->listorder = 'id';
		$this->initView();
		parent::_list();
		$list=$this->list;
		$this->assign('list',$list);
		$str = $this->fetch();
		$list = $this->view -> get('list');
		//如果不为超级管理员，则显示自己部门的。
		
		foreach($list as $k => $v){
			$str = str_replace('<!--sub#'.$v['id'].'-->', $this->membergrouphtml($v['id'],'membergroup'), $str);
		}
		
		if($pid!=0){$list='';}
		if(empty($list)){
			$str=$this->membergrouphtml($pid,'membergroup');
		}
		
		if(isset($_GET['keywords']) && $_GET['keywords'] != ''){
			$str=$this->membergrouphtml(-1,'membergroup');
		}
		
		$list = $_GET['list'];
		$empty = 1;
		$statu=$list?1:0;
		if($this->get('list')){
			$empty = 0;
		}
		die(json_encode(array('empty' => $empty,'tbody'=>$str,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this-> view -> get('pages'))));
	}
	private function membergrouphtml($pid = 0,$mytree){
		$this->dao = M('Member_position');
		$list = $this->dao -> where("site_id = ".__SITEID__." and pid= ".$pid) -> order('id') -> select();
		if($list){
			$this->assign('list', $list);
			$curstr = $this->fetch($mytree);
			foreach($this->list as $k => $v){
				$curstr = str_replace('<!--sub#'.$v['id'].'-->', $this->membergrouphtml($v['id'],$mytree), $curstr);
			}
			return $curstr;
		}else{
			if(isset($_GET['keywords']) && $_GET['keywords'] != ''){
				$map = "site_id = ".__SITEID__." and name like '%".$_GET['keywords']."%'";
				
			}else{
				$map = "site_id = ".__SITEID__." and memberpositionid like '%".$pid."%'";
			}
			
			$newlist=D('member')->where($map) ->select();
			$this->assign('list', $newlist);
			$curstr = $this->fetch($mytree);
			return $curstr;
		}
	}
	public function form(){
		$this->dao = M('Formcategory');
		if($this->_param('keywords')){
			$this->listmap.=" and site_id = '".__SITEID__."' and name like '%".$this->_param('keywords')."%'";
		}else{
			$this->listmap.=" and site_id = '".__SITEID__."' and pid=0";
		}
		$this->listorder = 'id';

		$this->initView();
		parent::_list();
		$list=$this->list;

		$this->assign('list',$list);
		$str = $this->fetch();
		$list = $this->view -> get('list');
		$empty = 1;
		$statu=$list?1:0;
		if($this->get('list')){
			$empty = 0;
		}
		die(json_encode(array('empty' => $empty,'tbody'=>$str,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this-> view -> get('pages'))));
	}
}